package com.dxf.bigdata.D05_spark_again

import org.apache.spark.rdd.RDD
import org.apache.spark.util.LongAccumulator
import org.apache.spark.{SparkConf, SparkContext}

/**
 *
 */
object 累加器 {

  def main(args: Array[String]): Unit = {

    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("app")
    sparkConf.set("spark.port.maxRetries", "100")
    val sc = new SparkContext(sparkConf)

    val rdd = sc.makeRDD(List(1, 2, 3, 4, 5, 6), 2)

    val i: Int = rdd.reduce(_ + _)
    println(i)

    var sum: Int = 0;
    // 分布式 sum=0 从driver 端传递到Executor端,计算后,driver端sum数据不变
    rdd.foreach(sum += _)
    println(sum)

    //累加器 把Executor端数据聚合到driver端
    val accSum: LongAccumulator = sc.longAccumulator("accSum")
    rdd.foreach(accSum.add(_))
    println(accSum.value)

    //    ====================
    val accSum2: LongAccumulator = sc.longAccumulator("accSum2")
    //少加 累加器不执行问题.map是转换算子,不会执行,除非有行动算子 .collect
    val value: RDD[Int] = rdd.map(x => {
      accSum2.add(x)
      x
    })
    //多加 2次调用collect,行动算子
    value.collect()
    value.collect()
    println(accSum2.value)

  }

}
